package com.gotobject.junit.internal.builders;

import com.gotobject.junit.Load;
import com.gotobject.junit.Response;
import com.gotobject.junit.Throughput;
import com.gotobject.junit.internal.runners.model.Explosion;
import com.gotobject.junit.runners.ConditionalJUnitPerfClassRunner;
import org.junit.runner.Runner;
import org.junit.runners.model.RunnerBuilder;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Huascar A. Sanchez (huascar.sanchez@gmail.com)
 */
public class PerformanceRunnerBuilder extends RunnerBuilder {
    private final Map<Class<?>, Explosion> testClassToExplosion;

    public PerformanceRunnerBuilder(Map<Class<?>, Explosion> testClassToExplosion){
        this.testClassToExplosion = testClassToExplosion;
    }

    private static List<Class<? extends Annotation>> getClubRoster(Class<?> testClass) {
        final List<Class<? extends Annotation>> clubRoster = new ArrayList<Class<? extends Annotation>>();
        for(Annotation each : testClass.getAnnotations()){
            clubRoster.add(each.annotationType());
        }
        return clubRoster;
    }

    private static boolean inTheClub(Class<?> testClass){
        final List<Class<? extends Annotation>> fullRoster = getClubRoster(testClass);
        return fullRoster.contains(Load.class) || fullRoster.contains(Response.class) || fullRoster.contains(Throughput.class);
    }

    @Override
    public Runner runnerForClass(Class<?> testClass) throws Throwable {
        if(inTheClub(testClass)){
            return new ConditionalJUnitPerfClassRunner(testClass);
        } else {
            final Iterable<Explosion> i = new ArrayList<Explosion>(testClassToExplosion.values());
            return new ConditionalJUnitPerfClassRunner(testClass, i);
        }
    }
}
